//
//  HJInformationController.m
//  KaiChat
//
//  Created by lx on 2024/3/11.
//

#import "HJInformationController.h"
#import "HMSegmentedControl.h"
#import "HJInformationChildController.h"
#import "HJNewsDailyController.h"
#import "HJRecommendController.h"
#import "HJInformationModel.h"
#import "HJBlockchainInformationController.h"
#import "HJPostInformationController.h"
#import "HJInformationPresent.h"
#import "HJVideoPlayController.h"
 

@interface HJInformationController ()<UIScrollViewDelegate>

@property (nonatomic, weak) HMSegmentedControl *segmentedControl;
@property (nonatomic, strong) NSMutableArray *types;
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) NSArray *moduleList;
@property (nonatomic, strong) NSMutableDictionary *modulePool;
@property (nonatomic, assign) BOOL isNeedRebuildModule;
@property (nonatomic, strong) NSMutableArray *listControllers;

@end

@implementation HJInformationController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UIView *lineView = [UIView addToView:self.navigationBar.contentView];
    lineView.backgroundColor = UIColor.tj_separatorColor;
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(0);
        make.height.offset(0.7);
        make.bottom.offset(0);
    }];
    
    [self getTypesComplete:^(NSArray *moduleList) {
        self.moduleList = moduleList;
        [self buildDataWithTypes:moduleList];
    }];

}

- (void)addSegmentedControl {
    
    [_segmentedControl removeFromSuperview];
    
    if (self.types.count == 0) {
        return;
    }
    
    NSMutableArray *segmentedDatas = @[].mutableCopy;
    for (NSDictionary *dict in self.types) {
        [segmentedDatas addObject:dict[@"name"]];
    }
    
    HMSegmentedControl *segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:segmentedDatas];
    segmentedControl.segmentEdgeInset = UIEdgeInsetsMake(0, 10, 0, 10);
    segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
    segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationBottom;
    segmentedControl.selectionIndicatorHeight = 1;
    segmentedControl.selectionIndicatorEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    segmentedControl.selectionIndicatorColor = UIColor.tj_333333Color;
    segmentedControl.segmentWidthStyle = HMSegmentedControlSegmentWidthStyleDynamic;
    segmentedControl.verticalDividerEnabled = NO;
    segmentedControl.backgroundColor = UIColor.clearColor;
    [segmentedControl setTitleTextAttributes:@{
        NSForegroundColorAttributeName : UIColor.tj_BEBDCAColor,
        NSFontAttributeName : UIFontMake(16)
    }];
    [segmentedControl setSelectedTitleTextAttributes:@{
        NSForegroundColorAttributeName : UIColor.tj_333333Color,
        NSFontAttributeName : UIFontMediumMake(16)
    }];
    [segmentedControl addTarget:self action:@selector(segmentedControlChangedValue:) forControlEvents:UIControlEventValueChanged];
    [self.navigationBar.contentView addSubview:segmentedControl];
    [segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(10);
        make.bottom.offset(0);
        make.height.offset(40);
    }];
    self.segmentedControl = segmentedControl;
}

- (void)buildDataWithTypes:(NSArray *)types {
    
    if (types.count) {
        [self.types removeAllObjects];
    }
    
    [types enumerateObjectsUsingBlock:^(NSDictionary *  _Nonnull dict, NSUInteger idx, BOOL * _Nonnull stop) {
 
        NSInteger type = [dict[@"type"] intValue];

        NSMutableDictionary *object = [NSMutableDictionary dictionaryWithDictionary:dict];
        HJInformationChildController *informationChildController = [self.modulePool objectForKey:toString(dict[@"type"])];
        if (informationChildController) {
            [object setValue:informationChildController forKey:@"controller"];
        } else {
            if (idx < 3) {
                if (type == 1 || type == 2) {
                    [object setValue:[[HJRecommendController alloc] init] forKey:@"controller"];
                } else if (type == 3) {
                    [object setValue:[[HJNewsDailyController alloc] init] forKey:@"controller"];
                }
            } else {
                [object setValue:[[HJBlockchainInformationController alloc] init] forKey:@"controller"];
            }
        }
        [self.types addObject:object];
    }];
 
    [self addSegmentedControl];

    [_scrollView removeFromSuperview];
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, KNavBarHight, KScreenWidth, KScreenHeight - KNavBarHight - TabBarHeight)].addTo(self.view);
    _scrollView.pagingEnabled = YES;
    _scrollView.bounces = NO;
    _scrollView.delegate = self;
    _scrollView.backgroundColor = UIColor.whiteColor;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width * self.types.count, _scrollView.frame.size.height);
        
    if (_isNeedRebuildModule) {
        [self.childViewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [obj removeFromParentViewController];
        }];
    }
    
    [self.types enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        HJInformationChildController *listController = obj[@"controller"];
        listController.dict = obj;
        [self addChildViewController:listController];
        [self.scrollView addSubview:listController.view];
        listController.view.frame = CGRectMake(KScreenWidth * idx, 0, KScreenWidth, _scrollView.tj_height);
        [self.modulePool setObject:listController forKey:toString(obj[@"type"])];
        [self.listControllers addObject:listController];
    }];
    
    if (self.types.count > 1) {
        [self.segmentedControl setSelectedSegmentIndex:1 animated:NO];
        [self.scrollView setContentOffset:CGPointMake(KScreenWidth, 0)];
        [self loadDataWithIndex:1];
    }
    
}

- (void)segmentedControlChangedValue:(HMSegmentedControl *)segmentedControl {
    [self.scrollView setContentOffset:CGPointMake(KScreenWidth * segmentedControl.selectedSegmentIndex, 0)];
    [self loadDataWithIndex:segmentedControl.selectedSegmentIndex];
}

- (void)loadDataWithIndex:(NSInteger)index {
    if (index >= self.listControllers.count) return;
    HJInformationChildController *listController = [self.listControllers objectAtIndex:index];
    [listController loadData];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat pageWidth = scrollView.frame.size.width;
    NSInteger page = scrollView.contentOffset.x / pageWidth;
    
    [self.segmentedControl setSelectedSegmentIndex:page animated:YES];
    [self loadDataWithIndex:page];
}

- (void)getTypesComplete:(void (^)(NSArray *moduleList))complete {
    NSArray *moduleList = [USERDEFAULTS objectForKey:moduleListKey];
    if (moduleList) {
        complete(moduleList);
    } else {
        [HJInformationPresent loadModuleListDataComplete:^(NSArray * _Nullable datas) {
            complete(datas);
        }];
    }
}

- (NSMutableArray *)types {
    if (!_types) {
        _types = [NSMutableArray array];
    }
    return _types;
}

- (NSMutableDictionary *)modulePool {
    if (!_modulePool) {
        _modulePool = [NSMutableDictionary dictionary];
    }
    return _modulePool;
}

- (NSMutableArray *)listControllers {
    if (!_listControllers) {
        _listControllers = [NSMutableArray array];
    }
    return _listControllers;
}

- (void)rebuildModule {

    NSArray *newsModuleList = [USERDEFAULTS objectForKey:moduleListKey];
    if (newsModuleList.count == 0) return;
    
    if (self.moduleList.count == newsModuleList.count) {
        
        NSMutableString *originalString = [NSMutableString string];
        for (NSDictionary *dict in self.moduleList) {
            [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                [originalString appendFormat:@"%@%@",obj, obj];
            }];
        }
        NSMutableString *string = [NSMutableString string];
        for (NSDictionary *dict in newsModuleList) {
            [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                [string appendFormat:@"%@%@",obj, obj];
            }];
        }
        if (![string isEqualToString:originalString]) {
            [self buildDataWithTypes:newsModuleList];
        }
    } else {
        [self buildDataWithTypes:newsModuleList];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (self.moduleList.count == 0) {
        [HJInformationPresent loadModuleListDataComplete:^(NSArray * _Nullable datas) {
            self.moduleList = datas;
            [self buildDataWithTypes:self.moduleList];
        }];
    } else {
        [self rebuildModule];
    }
}

@end
